<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouterPush } from '@/composables';
import { useGetPhone, useGetOpenid } from '@/hooks';
import { hideLoading, showLoading, showToast, showModal, getCurrentInstance } from '@tarojs/taro';
import { useNurseStore, useAuthStore } from '@/store';
import { storeToRefs } from 'pinia';
import { localStg } from '@/utils';
import { EventManager, EVENT_NAMES } from '@/utils/eventManager';
import { useImage } from '@/hooks';
import { ChannelUtils, getChannelName } from '@/utils/channel';
import { ChannelService } from '@/service/channel';
import { editDefaultHospital } from '@/service/api/nurse_user';
import Taro from '@tarojs/taro';

definePageConfig({
    navigationBarTitleText: '第三方登录'
});

const { toPrivacy, toHome, toNurselogin, toInfo, toAddrList, toGuardianList } = useRouterPush();
const { company } = storeToRefs(useNurseStore());
const authStore = useAuthStore();
const { nurseUser } = storeToRefs(authStore);

// 获取页面参数
const instance = getCurrentInstance();
const qudaoid = ref('');
const shopid = ref('');
const hospital = ref<any>({});

onMounted(async () => {
    // 获取URL参数
    const query = instance?.router?.params;
    if (query?.qudaoid) {
        qudaoid.value = query.qudaoid as string;
        // 渠道ID
        // 保存渠道ID到本地存储
        ChannelUtils.setChannelId(qudaoid.value);
        
        // 上报渠道访问信息
        // await ChannelService.reportChannelAccess();
    }
    if (query?.shopid) {
        shopid.value = query.shopid as string;
        // 店铺ID
        // 保存店铺ID到本地存储
        ChannelUtils.setShopId(shopid.value);
        const result = await ChannelService.getHospitalListByChannel();
        // console.log('result 医院', result);
        
        if (result) {
            const hospitalList = result.records || [];
            // 医院列表
            if (hospitalList.length > 0) {  
                hospital.value = hospitalList[0];
                Taro.setStorageSync('defaultHospital', JSON.stringify(hospital.value));
                localStg.set('sys_org_code', hospital.value.sysOrgCode);

                //设置默认医院
                try {
                    const nurseUser = localStg.get('nurseUser');
                    if (nurseUser && nurseUser.id) {
                        const response = await editDefaultHospital({
                            userId: nurseUser.id,
                            defaultHospital: hospital.value.id,
                            defaultHospitalName: hospital.value.name
                        });
                        
                        if (response.success) {
                            console.log('设置默认医院成功:', response);
                            // 更新本地用户信息
                            const updatedNurseUser = {
                                ...nurseUser,
                                defaultHospital: hospital.value.id,
                                defaultHospitalName: hospital.value.name
                            };
                            localStg.set('nurseUser', updatedNurseUser);
                        } else {
                            console.error('设置默认医院失败:', response);
                        }
                    } else {
                        console.warn('用户信息不存在，无法设置默认医院');
                    }
                } catch (error) {
                    console.error('设置默认医院出错:', error);
                }
                
                // 发送医院发生变化事件
                EventManager.emit(EVENT_NAMES.HOSPITAL_CHANGE, hospital.value);
                EventManager.emit(EVENT_NAMES.SYS_ORG_CHANGE, {
                    sysOrgCode: hospital.value.sysOrgCode,
                    hospitalId: hospital.value.id,
                    hospitalName: hospital.value.name
                });
            }
            //如果本地存在openid，自动跳到首页
            const openid = localStg.get('openid');
            // openid
            if (openid) {
                // 检查是否有用户信息
                const nurseUser = localStg.get('nurseUser');
                if (nurseUser && nurseUser.name) {
                    Taro.reLaunch({
                        url: '/pages/index/index'
                    });
                } else {
                    // 有openid但没有用户信息，尝试获取用户信息
                    // 有openid但缺少用户信息，尝试获取
                    // 这里可以调用获取用户信息的逻辑
                }
            }
        }
    }
});

async function getPhoneNumber(e: any) {
    // e
    localStg.remove('nurseNurses');
    localStg.remove('nurse_openid');
    const phoneCode = e?.detail?.code;

    showLoading({ title: '正在登录...' });

    const flag = await useGetPhone(phoneCode);

    if (flag) {
        hideLoading();
        // 登录成功后跳转到首页，并携带渠道信息
        toHome();
    } else {
        hideLoading();
        showToast({
            title: '取用户信息失败',
            icon: 'error',
            duration: 1500
        });
    }
}

// 检查用户信息是否完整
function checkUserInfoComplete() {
    const user = nurseUser.value;
    const missingItems: string[] = [];
    
    // 检查注册信息（姓名、手机号、身份证号）
    const hasIdCard = user.idcard || user.idCard;
    if (!user.name || !user.phone || !hasIdCard) {
        missingItems.push('注册信息');
    }
    
    // 检查诊疗卡/居家护理地址
    const hasAddr = (user.nurseUserAddrList && user.nurseUserAddrList.length > 0) || 
                    (user.nurseHomeAddrList && user.nurseHomeAddrList.length > 0);
    if (!hasAddr) {
        missingItems.push('诊疗卡/居家护理地址');
    }
    
    // 检查监护人
    if (!user.nurseUserFamilyList || user.nurseUserFamilyList.length === 0) {
        missingItems.push('监护人');
    }
    
    return {
        isComplete: missingItems.length === 0,
        missingItems
    };
}

// 显示信息不完整提醒
function showIncompleteInfoModal(missingItems: string[]) {
    const itemsText = missingItems.join('、');
    showModal({
        title: '温馨提示',
        content: `检测到您还未完善以下信息：${itemsText}。请先前往完善相关信息，以便更好地使用服务。`,
        confirmText: '去完善',
        cancelText: '稍后再说',
        success: (res) => {
            if (res.confirm) {
                // 按优先级跳转：注册信息 > 诊疗卡/居家护理地址 > 监护人
                if (missingItems.includes('注册信息')) {
                    toInfo();
                } else if (missingItems.includes('诊疗卡/居家护理地址')) {
                    toAddrList();
                } else if (missingItems.includes('监护人')) {
                    toGuardianList();
                }
            } else {
                // 用户选择稍后再说，直接跳转到首页
                toHome();
            }
        }
    });
}

async function gotologin() {
    localStg.remove('nurseNurses');
    localStg.remove('nurse_openid');
    if (!checkbox.value) {
        showToast({
            title: '请先阅读并同意用户授权协议',
            icon: 'error',
            duration: 1500
        });
        return;
    }   
    showLoading({ title: '正在登录...' });

    const flag = await useGetOpenid();

    if (flag) {
        hideLoading();
        // 等待用户信息更新到 store
        await new Promise(resolve => setTimeout(resolve, 300));
        
        // 检查用户信息是否完整
        const checkResult = checkUserInfoComplete();
        
        if (!checkResult.isComplete) {
            // 信息不完整，弹出提醒
            showIncompleteInfoModal(checkResult.missingItems);
        } else {
            // 信息完整，直接跳转到首页
            toHome();
        }
    } else {
        hideLoading();
        showToast({
            title: '取用户信息失败',
            icon: 'error',
            duration: 1500
        });
    }
}

const checkbox = ref(false);
</script>

<template>
    <basic-layout>
        <view class="w-375px h-full flex-col-center fixed-lt">
            <view class="w-375px h-full flex-col-center">
                <view class="w-260px h-full flex-col-center">
                    <!-- 渠道标识 -->
                    <!-- <view v-if="qudaoid" class="mb-4 p-2 bg-#f0f9ff rounded-lg border border-#3b82f6">
                        <view class="text-center text-#3b82f6 text-sm">
                            渠道来源: {{ getChannelName(qudaoid) }} ({{ qudaoid }})
                        </view>
                    </view> -->
                    <view v-if="hospital.name" class="mb-4 p-4">
                        <view class="text-center font-bold text-xl">
                            {{ hospital.name }}
                        </view>
                    </view>
                    <view class="flex-center">
                        
                        <image v-if="hospital.logo" :src="useImage(hospital.logo)" style="height: 100px; width: 100px" />
                        <logo v-else style="height: 100px; width: 100px" />
                    </view>
                    <view class="mt-3 font-bold text-#059669 text-lg text-#000">{{ company.departName }}</view>
                    <view class="mt-3 text-#000">{{ company.fax }}</view>
                    <view class="mt-3 font-bold text-#059669">
                        <view class="w-280px flex-center justify-around mt-3">
                            <view
                                class="bg-gradient-to-bl from-#f39c12/60 via-#2ecc71:80 to-#9b59b6_70 w-120px b-rounded-2 h-60px flex-center justify-around">
                                <view class="flex-col-center">
                                    <view class="i-local-online w-30px h-30px text-#059669" />
                                </view>
                                <view class="flex-col-center">
                                    <view class="">线上申请</view>
                                    <view class="">居家服务</view>
                                </view>
                            </view>
                            <view
                                class="bg-gradient-to-bl from-#f39c12/60 via-#2ecc71:80 to-#9b59b6_70 w-120px b-rounded-2 h-60px flex-center justify-around">
                                <view class="flex-col-center">
                                    <view class="i-local-protect w-30px h-30px text-#059669" />
                                </view>
                                <view class="flex-col-center">
                                    <view>专业医护</view>
                                    <view>安全放心</view>
                                </view>
                            </view>
                        </view>
                        <view class="w-280px flex-center justify-around mt-3">
                            <view
                                class="bg-gradient-to-bl from-#f39c12/60 via-#2ecc71:80 to-#9b59b6_70 w-120px b-rounded-2 h-60px flex-center justify-around">
                                <view class="flex-col-center">
                                    <view class="i-local-medal w-30px h-30px text-#059669" />
                                </view>
                                <view class="flex-col-center">
                                    <view>管理完善</view>
                                    <view>服务规范</view>
                                </view>
                            </view>
                            <view
                                class="bg-gradient-to-bl from-#f39c12/60 via-#2ecc71:80 to-#9b59b6_70 w-120px b-rounded-2 h-60px flex-center justify-around">
                                <view class="flex-col-center">
                                    <view class="i-local-service w-30px h-30px text-#059669" />
                                </view>
                                <view class="flex-col-center">
                                    <view>三方投保</view>
                                    <view>防控风险</view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="mt-6 w-full flex-col-center">
                        <nut-button v-if="!checkbox" color="#3d8944" size="large" plain
                            class="important:w-280px font-bold" @click.stop="gotologin">
                            授权登录
                        </nut-button>
                        <nut-button v-else color="#3d8944" size="large"
                            class="important:w-280px font-bold" @click.stop="gotologin">
                            授权登录
                        </nut-button>
                        <view class="my-6 text-gray-500" @click="toHome">暂不授权</view>
                        <!-- <button 
                            open-type="getPhoneNumber" 
                            @getphonenumber="getPhoneNumber"
                            class="auth-button"
                            style="width: 280px; height: 40px; background: #059669; color: white; border: none; border-radius: 4px;"
                        >
                            获取手机号
                        </button> -->
                    </view>
                    <view class="w-full flex-center">
                        <nut-checkbox v-model="checkbox" />
                        <text class="text-12px w-full">
                            本人已审慎阅读、充分理解且同意
                            <i class="text-#059669" @click="toPrivacy()">《用户授权协议》</i>
                            中的全部条款内容
                        </text>
                    </view>
                </view>
            </view>
        </view>
    </basic-layout>
</template>

<style scoped></style>
